//
//  ScreenModeViewController.swift
//  CheckmeRing
//
//  Created by 董鹏 on 2022/2/17.
//

import UIKit
import SVProgressHUD
import VTO2Lib

class ScreenModeViewController: RViewController {

    let data = ["標準", "常にオン"]
    var selectIndex = 0
    
    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = hexColor("F9F9F9")
        self.tableView.register(UINib.init(nibName: "ScreenTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: "ScreenTableViewCell")
        self.tableView.layer.cornerRadius = 8
        self.tableView.separatorStyle = .none
        self.tableView.isScrollEnabled = false
        self.tableView.rowHeight = ScreenRowHeight
        
        if let info = RManager.manager.info {
            // 0-Standard, 1-Always off, 2-Always on.
            VTO2Communicate.sharedInstance().delegate = self
            selectIndex = Int(info.lightingMode) == 0 ? 0 : 1
        }
        self.tableView.reloadData()
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }

}

extension ScreenModeViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ScreenTableViewCell") as! ScreenTableViewCell
        cell.selectionStyle = .none
        cell.titleLabel.text = data[indexPath.row]
        cell.separLine.isHidden = indexPath.row == data.count - 1
        cell.selectIcon.image = UIImage.init(named: indexPath.row == self.selectIndex ? "select" : "disSelect")
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // 屏幕是否常亮
        if indexPath.row == 0 {
            self.setDeviceScreenMode(content: "0")
        }
        if indexPath.row == 1 {
            self.setDeviceScreenMode(content: "2")
        }
        self.selectIndex = indexPath.row
    }
    
    // 0-Standard, 1-Always off, 2-Always on.
    // 2-High    1-Medium     0-Low
    func setDeviceScreenMode(content: String) {
        if RManager.manager.currentDevice != nil {
            SVProgressHUD.show()
            RManager.manager.info?.lightingMode = content
            VTO2Communicate.sharedInstance().begin(to: VTParamTypeLightingMode, content: content)
        }
        self.tableView.reloadData()
    }
    
}

extension ScreenModeViewController: VTO2CommunicateDelegate {
    
    func commonResponse(_ cmdType: VTCmdType, andResult result: VTCommonResult) {
        SVProgressHUD.dismiss()
    }
    
}
